from datetime import datetime

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from module.models import Module
from module.serializers import ModuleSerializers, ModuleDetailSerializersSave
from Stage.models import Stage
from Stage.serializers import StageSerializers

# Create your views here.

class ModuleViewSave(ModelViewSet):
    queryset = Module.objects.all()
    serializer_class = ModuleDetailSerializersSave
    # 添加模块
    def create(self, request, *args, **kwargs):
        # 查询模块 是否 已添加 (删除状态是False,查询没有删除的名字是否有重名的)
        queryset = self.get_queryset().filter(name=request.data['name'], is_delete=False)
        print(queryset,"////////////////")
        if queryset:
            return Response(data={"message": "模块名已存在"}, status=status.HTTP_400_BAD_REQUEST)
        return super().create(request, *args, **kwargs)



class ModuleView(ModelViewSet):
    queryset = Module.objects.all()
    serializer_class = ModuleSerializers

    # 分页
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = 'rows'

    # 查询所有的模块
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(is_delete=False)
        # 进行分页
        paginate = self.paginate_queryset(queryset)
        if paginate is None:
            return Response(data={"message": "该请求必须进行分页操作"}, status=status.HTTP_400_BAD_REQUEST)
        # 对分页后的结果 进行序列化
        serializer = self.get_serializer(paginate, many=True)
        # 返回分页后的结果
        return self.get_paginated_response(serializer.data)

    #批量逻辑删除
    @action(methods=['DELETE'], detail=False,url_path='batch-remove-Module', url_name='batch-remove-Module')
    def batch_remove_Module(self, request, *args, **kwargs):
        #批量逻辑删除
        self.get_queryset().filter(pk__in=request.data).update(is_delete=True,delete_time=datetime.now())
        return Response(status=status.HTTP_204_NO_CONTENT)

    def destroy(self, request, *args, **kwargs):
        # 删除模块
        url = request.path
        id = url.rsplit("/")[-1]
        queryset = self.get_queryset().filter(id=id)
        if queryset:
            queryset.update(is_delete=True, update_time=datetime.now())
            return Response(data={"message":"删除成功"},status=status.HTTP_200_OK)
        return Response(data={"message":"删除失败"},status=status.HTTP_400_BAD_REQUEST)

    #修改模块(获取查询数据)
    @action(methods=['GET'], detail=False, url_path='edit-module', url_name='edit-module')
    def get_edit_module(self, request, *args, **kwargs):
        # 根据id查询数据
        # 正确获取GET请求的查询参数
        stage=Stage.objects.all()
        serializers=StageSerializers(stage,many=True)
        if serializers.data:
            return Response(data=serializers.data,status=status.HTTP_200_OK)
        # ids = request.query_params.get('id')  #获取模块的id
        # if ids is not None:
        #     queryset = self.get_queryset().get(id=ids, is_delete=False)
        #     stage_id=queryset.stage_id #查询阶段的id
        #     if stage_id:  # 查询阶段的id
        #
        #         return Response(data=serializer.data, status=status.HTTP_200_OK)
        #     else:
        #         return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码
        # else:
        #     return Response(status=status.HTTP_400_BAD_REQUEST)  # 如果没有提供id参数，返回400状态码

    #修改模块
    @action(methods=['POST'], detail=True, url_name='update-module', url_path='update-module')
    def UpdateModule(self, request, *args, **kwargs):
        # queryset = self.get_queryset().get(id=kwargs["pk"], is_delete=False)
        instance = self.get_object()
        serializer = ModuleDetailSerializersSave(instance=instance, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        if serializer.data:
            return Response(data=serializer.data, status=status.HTTP_200_OK)
        return Response(status=status.HTTP_404_NOT_FOUND)  # 如果没有找到对应的记录，返回404状态码

    @action(methods=['GET'], detail=False, url_path='Moduleable', url_name='Moduleable')
    def Moduleable(self, request, *args, **kwargs):
        # 查询所有可用的阶段
        stage = request.query_params.get('stage')
        print(stage)
        queryset = self.get_queryset().filter(stage_id = stage)
        print(queryset)
        # 序列化满足条件的数据
        serialize = self.get_serializer(queryset, many=True)
        return Response(data=serialize.data, status=status.HTTP_200_OK)

